package com.avic.rong.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseFragment;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.adapter.show.WenDaAdapter;
import com.avic.rong.bean.show_bean.WenDaBean;
import com.avic.rong.fragment.showapi.WenDaApi;
import com.avic.rong.listener.RocketOnScrollListener;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.questionOrAnswer.activity.QuestionActivity;
import com.avic.rong.questionOrAnswer.api.GetInfoApi;
import com.avic.rong.questionOrAnswer.bean.HomeInfoBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by TSJ-2018-0492 on 2019/8/20.
 */

public class FragmentWenDa extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener {


    private TextView wendaName;
    private TextView wendaGo, wenda_go_mouth;
    private RecyclerView wendaRec;
    private LinearLayout ll_person_wenda;
    private ImageView wendaIcon, type_8_daV;
    private List<HomeInfoBean> listData = new ArrayList<>();
    public boolean isRefresh = false;
    private WenDaApi wenDaApi;
    private List<WenDaBean> wenDaBeanList = new ArrayList<>();
    private WenDaAdapter wenDaAdapter;
    private GetInfoApi getInfoApi;
    public SmartRefreshLayout refreshLayout;
    private LoadingLayout loading_layout;
    private int currentPageNumber = 1;
    public static boolean is_Resum = false;

    public NestedScrollView nestedScrollView;
    private String mTitle;
    private Context mContext;

    public static FragmentWenDa getInstance(String title, Context context) {
        FragmentWenDa sf = new FragmentWenDa();
        sf.mTitle = title;
        sf.mContext = context;
        return sf;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.wenda_frag;
    }

    @Override
    protected void initView() {
        wendaName = fragmentView.findViewById(R.id.wenda_name);
        wendaIcon = fragmentView.findViewById(R.id.wenda_icon);
        type_8_daV = fragmentView.findViewById(R.id.type_8_daV);
        wendaGo = fragmentView.findViewById(R.id.wenda_go);
        wendaRec = fragmentView.findViewById(R.id.wenda_rec);
        wenda_go_mouth = fragmentView.findViewById(R.id.wenda_go_mouth);

        ll_person_wenda = fragmentView.findViewById(R.id.ll_person_wenda);
        loading_layout = fragmentView.findViewById(R.id.loading_layout);
        //监听滚动
        nestedScrollView = fragmentView.findViewById(R.id.nest_scrollview);
        nestedScrollView.setOnScrollChangeListener(new RocketOnScrollListener(((MainActivity) getActivity())));

        loading_layout.hideReturnButton();
        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loading_layout.setStatus(LoadingLayout.LOADING);
                HttpManager.getInstance().doHttpDeal(getInfoApi);
            }

            @Override
            public void onReturn(View v) {

            }
        });

        wendaGo.setOnClickListener(this);
        wenda_go_mouth.setOnClickListener(this);
        wendaIcon.setOnClickListener(this);
        wendaName.setOnClickListener(this);
        if (SharedPreferencesUtil.isLogin()) {
            ll_person_wenda.setVisibility(View.VISIBLE);
            wendaIcon.setVisibility(View.VISIBLE);
            wendaName.setVisibility(View.VISIBLE);
            wendaGo.setVisibility(View.VISIBLE);
        } else {

            wendaIcon.setVisibility(View.GONE);
            wendaName.setVisibility(View.GONE);
            wendaGo.setVisibility(View.GONE);
            ll_person_wenda.setVisibility(View.GONE);
        }

        refreshLayout = fragmentView.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        wendaRec.setLayoutManager(new LinearLayoutManager(getActivity()));
        wenDaAdapter = new WenDaAdapter(getActivity());
        wendaRec.setAdapter(wenDaAdapter);
        listData.clear();
        wenDaBeanList.clear();
        initData();
    }


    public static void setIs_Resum(boolean is_Resum) {
        FragmentWenDa.is_Resum = is_Resum;
    }

    public void initData() {
        wenDaApi = new WenDaApi((MainActivity) getActivity(), httpOnNextListener);
        wenDaApi.setPageNo(currentPageNumber);
        wenDaApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(wenDaApi);


        getInfoApi = new GetInfoApi((MainActivity) getActivity(), simpleOnNextListener);
        if (SharedPreferencesUtil.isLogin()){
            Map<String, String> map = new HashMap<>();
            map.put("token", SharedPreferencesUtil.getLoginToken());
            getInfoApi.setCache(false);
            getInfoApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(getInfoApi);
        }

    }


    @Override
    protected void addListener() {

    }


    @Override
    public void onResume() {
//        if (SharedPreferencesUtil.isLogin()) {
//            map.put("token", SharedPreferencesUtil.getInstance().getLogintoken());
//            getInfoApi.setCache(false);
//            getInfoApi.setMap(map);
//            HttpManager.getInstance().doHttpDeal(getInfoApi);
//            ll_person_wenda.setVisibility(View.VISIBLE);
//            wendaIcon.setVisibility(View.VISIBLE);
//            wendaName.setVisibility(View.VISIBLE);
//            wendaGo.setVisibility(View.VISIBLE);
//        } else {
//            wendaIcon.setVisibility(View.GONE);
//            wendaName.setVisibility(View.GONE);
//            wendaGo.setVisibility(View.GONE);
//            ll_person_wenda.setVisibility(View.GONE);
//        }
//
        if (is_Resum) {
            initData();
            is_Resum = false;
        }
        super.onResume();
    }

    //回答列表
    HttpOnNextListener<BaseResultEntity> httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(baseResultEntity.getCode())) {
                return;
            }
            if (isRefresh) {
                wenDaBeanList.clear();
            }
            List<WenDaBean> data = (List<WenDaBean>) baseResultEntity.getData();
            if (data != null) {
                wenDaBeanList.addAll(data);
            }
            wenDaAdapter.setData(wenDaBeanList);
            wenDaAdapter.notifyDataSetChanged();

            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (wenDaBeanList.size() <= 0){
                if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                    loading_layout.setStatus(LoadingLayout.NO_NETWORK);
                } else {
                    loading_layout.setStatus(LoadingLayout.ERROR);
                }
            }

            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }


        }
    };
    //融融号主页发布等数据
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            loading_layout.setStatus(LoadingLayout.SUCCESS);

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(subjects.getMsg());
                return;
            }

            listData = (List<HomeInfoBean>) subjects.getData();
            HomeInfoBean.DataBean data = listData.get(0).getData();
            int isV = data.getIsV();
            if (isV == 1) {
                type_8_daV.setVisibility(View.VISIBLE);
            }
            HomeInfoBean.DataBean infoData = listData.get(1).getData();
            Glide.with(getActivity()).load(infoData.getLogo())
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .error(R.mipmap.deafult_image_header)
                    .into(wendaIcon);


            if (infoData != null) {
                wendaName.setText(infoData.getUserName());
            }
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
        }


        @Override
        public void onError(final Throwable e) {
            loading_layout.setStatus(LoadingLayout.ERROR);
            Log.e("cjx", e.getMessage());
        }
    };


    private void goRongRong(int type) {
        Intent intent = new Intent(getActivity(), PersonalHomeActivity.class);
        intent.putExtra("enterType", type + "");
        startActivity(intent);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        currentPageNumber = currentPageNumber + 1;
        wenDaApi.setPageNo(currentPageNumber);
        HttpManager.getInstance().doHttpDeal(wenDaApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        isRefresh = true;
        currentPageNumber = 1;
        wenDaApi.setPageNo(currentPageNumber);
        HttpManager.getInstance().doHttpDeal(wenDaApi);

        if (SharedPreferencesUtil.isLogin()){
            Map<String, String> map = new HashMap<>();
            map.put("token", SharedPreferencesUtil.getLoginToken());
            getInfoApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(getInfoApi);
        }




        if (SharedPreferencesUtil.isLogin()) {
            ll_person_wenda.setVisibility(View.VISIBLE);
            wendaIcon.setVisibility(View.VISIBLE);
            wendaName.setVisibility(View.VISIBLE);
            wendaGo.setVisibility(View.VISIBLE);
            wenda_go_mouth.setVisibility(View.VISIBLE);

        } else {
            wendaIcon.setVisibility(View.GONE);
            wendaName.setVisibility(View.GONE);
            wendaGo.setVisibility(View.GONE);
            wenda_go_mouth.setVisibility(View.GONE);
            ll_person_wenda.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wenda_icon:
                goRongRong(0);
                break;
            case R.id.wenda_name:
                goRongRong(0);
                break;
            case R.id.wenda_go:
                //type 1  跳转个人主页默认选中问答
                goRongRong(1);
                break;
            case R.id.wenda_go_mouth:
                //去提问
                startActivity(QuestionActivity.queryIntent(getActivity(), null));
                break;
        }
    }
}
